package com.enjoyread.api.filter;

import com.alibaba.fastjson.JSON;
import com.enjoyread.common.config.RedisKeyConfig;
import com.enjoyread.common.config.SystemConfig;
import com.enjoyread.core.entity.User;
import com.enjoyread.core.utils.JedisUtil;
import org.springframework.context.annotation.ComponentScan;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author: JC
 * @time: 2021/10/19 19:34
 * @description:
 */
//实现过滤器 实现令牌的续期
@WebFilter("/*")
@ComponentScan
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求的令牌
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String togen = request.getHeader(SystemConfig.HEADER_TOKEN);
        //校验令牌是否存在
        String key = RedisKeyConfig.LOGIN_TOKEN+togen;
        if(JedisUtil.checkKey(key)){
            //通过token获得手机号再通过手机号找到对应的键
            //将两个键值重新定时30分钟
            User user = JSON.parseObject(JedisUtil.getStr(key), User.class);
            String phone=user.getPhone();
            JedisUtil.expire(RedisKeyConfig.LOGIN_PHONE+phone,RedisKeyConfig.LOGIN_TOKEN_TIME);
            JedisUtil.expire(key,RedisKeyConfig.LOGIN_TOKEN_TIME);
            //自动解析令牌，获取uid，存储到消息头上
            request.newPushBuilder().addHeader(SystemConfig.HEADER_TOKEN_UID,user.getId()+"");

        }
        //放行
        filterChain.doFilter(request,servletResponse);
    }

    @Override
    public void destroy() {
    }
}
